{% extends "button.html" %}
{% block title %}
    <title>样本建库信息</title>
{% endblock %}


{% block content %}
    <div class="jumbotron">
        <h1>甲基化早筛项目数据库管理系统Demo</h1>
        <h4>样本建库信息表</h4>
    </div>
{% endblock %}

{% block plot %}
    <div class="row">
        <div id="plot_highcharts" style="width: 550px; height: 400px; margin: 0 auto" class="col-9"></div>
        <div id="plot_button" class="form-group col-3">
            <label for="plot_highcharts_field"> 请选择用于画图的关键字段</label>
            <select class="form-control" id="plot_highcharts_field" name="plot_highcharts_field">
                <option value="clinical_boolen" selected="selected">是否临床</option>
                <option value="label">样本标签</option>
                <option value="LB_date">建库日期</option>
                <option value="LB_method">建库方法</option>
                <option value="kit_batch">试剂批次</option>
                <option value="mass">起始量</option>
                <option value="pcr_cycles">PCR循环数</option>
                <option value="LB_con">文库浓度</option>
                <option value="LB_vol">文库体积</option>
                <option value="operator">操作人</option>
            </select>
        </div>
    </div><br>
{% endblock %}

{% block table %}
    <!-- datatables -->
    <table id="table_id" class="display">
        <thead>
        <tr>
            <th>索引</th>
            <th>建库编号</th>
            <th>样本编号</th>
            <th>DNA提取编号</th>
            <th>管上编号</th>
            <th>是否临床</th>
            <th>文库名</th>
            <th>样本标签</th>
            <th>index列表</th>
            <th>建库日期</th>
            <th>建库方法</th>
            <th>试剂批次</th>
            <th>样本浓度</th>
            <th>起始量</th>
            <th>PCR循环数</th>
            <th>文库浓度</th>
            <th>文库体积</th>
            <th>操作人</th>
            <th>备注</th>
            <th>上次修改时间</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        </thead>
    </table>
{% endblock %}

{% block ModalForm %}
    <div id="usageForm">
        <div class="form-group InventoryForm">
            <span><a class="text-danger front-weight-bold">* </a>
                    <label for="dna_id"> DNA提取编号</label></span>
            <input type="text" class="form-control" id="dna_id" name="dna_id"
                   placeholder="请输入DNA提取编号，必填" required="true">
        </div>
        <div class="form-group">
            <span><a class="text-danger front-weight-bold">* </a>
            <label for="singleLB_id"> 建库编号</label></span>
            <input type="text" class="form-control" id="singleLB_id" name="singleLB_id"
                   placeholder="请输入建库编号，必填" required="true">
        </div>
        <div class="form-group">
            <label for="LB_date"> 建库日期</label>
            <input type="date" class="form-control" id="LB_date" name="LB_date"
                   placeholder="请输入建库日期，默认：2000-01-01" value="2000-01-01">
        </div>
        <div class="form-group">
            <label for="mass"> 起始量(ng)</label>
            <input type="number" step="0.01" class="form-control" id="mass" name="mass"
                   placeholder="请输入起始量(ng)，默认：0" value="0">
        </div>
    </div>
    <div class="form-group">
        <label for="LB_method"> 建库方法</label>
        <select class="form-control" id="LB_method" name="LB_method" required="true">
            <option value="2.2" selected="selected">2.2</option>
            <option value="2.1">2.1</option>
            <option value="2.0">2.0</option>
            <option value="1.0">1.0</option>
        </select>
    </div>
    <div class="form-group">
        <label for="pcr_cycles"> PCR循环数</label>
        <input type="number" class="form-control" id="pcr_cycles" name="pcr_cycles"
               placeholder="请输入PCR循环数，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="LB_con"> 文库浓度(ng/ul)</label>
        <input type="number" step="0.01" class="form-control" id="LB_con" name="LB_con"
               placeholder="请输入文库浓度(ng/ul)，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="LB_vol"> 文库体积(ul)</label>
        <input type="number" step="0.01" class="form-control" id="LB_vol" name="LB_vol"
               placeholder="请输入文库体积(ul)，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="operator"> 操作人</label>
        <input type="text" class="form-control" id="operator" name="operator"
               placeholder="请输入操作人，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="singleLB_name"> 文库名</label>
        <input type="text" class="form-control" id="singleLB_name" name="singleLB_name"
               placeholder="请输入文库名，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="label"> 样本标签</label>
        <select type="text" class="form-control" id="label" name="label" required="true">
            <option value="P" selected="selected">P</option>
            <option value="T">T</option>
            <option value="Frg_gDNA">Frg_gDNA</option>
        </select>
    </div>
    <div class="form-group">
        <label for="barcodes"> index列表</label>
        <input type="text" class="form-control" id="barcodes" name="barcodes"
               placeholder="请输入index列表，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="tube_id"> 管上编号</label>
        <input type="text" class="form-control" id="tube_id" name="tube_id"
               placeholder="请输入管上编号，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="clinical_boolen"> 是否临床</label>
        <select class="form-control" id="clinical_boolen" name="clinical_boolen" required="true">
            <option value="是" selected="selected">是</option>
            <option value="否">否</option>
        </select>
    </div>
    <div class="form-group">
        <label for="kit_batch"> 试剂批次</label>
        <input type="text" class="form-control" id="kit_batch" name="kit_batch"
               placeholder="请输入试剂批次，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="others"> 备注</label>
        <input type="text" class="form-control" id="others" name="others"
               placeholder="请输入备注，默认：无" value="无">
    </div>
{% endblock %}

{% block extra_js %}
    <script>
        $(document).ready(function () {
            let id = 0;
            let singleLB_id;
            let id2;
            let mass0;
            let dnaid;
            let url = '/api/LibraryInfo/';
            let url2 = '/api/DNAUsageRecordInfo/';
            let url3 = '/api/DNAInventoryInfo/';
            let dataModelForm;
            let fieldForPie = $('#plot_highcharts_field');

            function MyModelInit(title_name, data) {
                dataModelForm = data;
                if (title_name === '更新') {
                    $('#singleLB_id').val(data['singleLB_id']);
                    $('#dna_id').val(data['dna_id']);
                    $('#LB_date').val(data['LB_date']);
                    $('#mass').val(data['mass']);
                    $('#LB_method').val(data['LB_method']);
                    $('#pcr_cycles').val(data['pcr_cycles']);
                    $('#LB_con').val(data['LB_con']);
                    $('#LB_vol').val(data['LB_vol']);
                    $('#operator').val(data['operator']);
                    $('#singleLB_name').val(data['singleLB_name']);
                    $('#label').val(data['label']);
                    $('#barcodes').val(data['barcodes']);
                    $('#others').val(data['others']);
                    $('#tube_id').val(data['tube_id']);
                    $('#clinical_boolen').val(data['clinical_boolen']);
                    $('#kit_batch').val(data['kit_batch']);
                    $('#type').val('edit');
                    $('#modal_title').text('更新');
                } else {
                    $('#singleLB_id').val("");
                    $('#dna_id').val("");
                    $('#LB_date').val("2000-01-01");
                    $('#mass').val("");
                    $('#LB_method option:first').prop("selected", 'selected');
                    $('#pcr_cycles').val("");
                    $('#LB_con').val("");
                    $('#LB_vol').val("");
                    $('#operator').val("");
                    $('#singleLB_name').val("");
                    $('#label option:first').prop("selected", 'selected');
                    $('#barcodes').val("");
                    $('#others').val("");
                    $('#tube_id').val("");
                    $('#clinical_boolen option:first').prop("selected", 'selected');
                    $('#kit_batch').val("");
                    $('#type').val('new');
                    $('#modal_title').text('新增');
                }
            }

            let getDNAConDict = function () {
                let ExtractInfo_all = $.ajax({
                    url: '/api/ExtractInfo/', dataType: 'json', contentType: "application/json",
                    type: "get", async: false
                }).responseJSON;
                let res = {};
                $.each(ExtractInfo_all, function (index, value) {
                    res[value.dna_id] = value.dna_con;
                });
                return res;
            };

            let DNAConDict = getDNAConDict();

            let table = $('#table_id').DataTable({
                "language": {
                    "lengthMenu": "选择每页 _MENU_ 展示 ",
                    "zeroRecords": "未找到匹配结果--抱歉",
                    "info": "当前显示第 _PAGE_ 页结果，共 _PAGES_ 页",
                    "infoEmpty": "没有数据",
                    "search": "搜索",
                    "infoFiltered": "(获取 _MAX_ 项结果)",
                    "paginate": {
                        "first": "首页",
                        "previous": "上一页",
                        "next": "下一页",
                        "last": "末页"
                    }
                },
                "scrollY": "5000px",
                "scrollCollapse": true,
                "scrollX": true,
                "pagingType": "full_numbers",
                fixedColumns: true,
                rowReorder: true,
                colReorder: true,
                searching: true,
                select: true,
                dom: 'lB<"clear">frtip',
                buttons: [
                    {
                        extend: 'colvisGroup',
                        text: '显示前5列',
                        show: [0, 1, 2, 3, 4, 5, 21],
                        hide: [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
                    },
                    {
                        extend: 'colvisGroup',
                        text: '显示全部列',
                        show: ':hidden',
                    },
                    {
                        text: '指定显示列', extend: 'colvis',
                        postfixButtons: ['colvisRestore'],
                        columnText: function (dt, idx, title) {
                            return (idx + 1) + ': ' + title;
                        }
                    },
                    {
                        extend: 'selectAll',
                        text: '全选'
                    }, {
                        extend: 'selectRows',
                        text: '选择多行'
                    }, {
                        extend: 'selectColumns',
                        text: '选择多列'
                    }, {
                        extend: 'selectCells',
                        text: '选择多个单元格'
                    }, {
                        extend: 'selectNone',
                        text: '取消当前选择'
                    },
                    {
                        extend: 'copy',
                        text: '复制到剪切板'
                    }, {
                        extend: 'csv',
                        text: '输出到csv'
                    }
                ],
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "全部"]],
                "serverSide": true,
                "processing": true,
                "ajax": "/api/LibraryInfo/?format=datatables",
                "deferRender": true,
                "columns": [
                    {
                        data: 'index',
                        width: "1%",
                        // 若想前端显示的不一样，则需要"render"函数
                        'render': function (data, type, full, meta) {
                            return meta.row + 1 + meta.settings._iDisplayStart;
                        }
                    },
                    {"data": "singleLB_id"},
                    {"data": "sample_id"},
                    {"data": "dna_id"},
                    {"data": "tube_id"},
                    {"data": "clinical_boolen"},
                    {"data": "singleLB_name"},
                    {"data": "label"},
                    {"data": "barcodes"},
                    {"data": "LB_date"},
                    {"data": "LB_method"},
                    {"data": "kit_batch"},
                    {
                        "data": "dna_id",
                        render: function (data, type, row, meta) {
                            return DNAConDict[data];
                        }
                    },
                    {"data": "mass"},
                    {"data": "pcr_cycles"},
                    {"data": "LB_con"},
                    {"data": "LB_vol"},
                    {"data": "operator"},
                    {"data": "others"},
                    {"data": "last_modify_date"},
                    {"data": "created"},
                    {
                        "data": null,
                        "defaultContent": '<button type="button" class="btn btn-info">更新</button>' + '&nbsp;&nbsp' +
                            '<button type="button" class="btn btn-danger">删除</button>'
                    }
                ]
            });
            table.button(0).trigger();


            $('#table_id tbody').on('click', 'button', function () {
                let data = table.row($(this).parents('tr')).data();
                let class_name = $(this).attr('class');
                id = data['index'];
                dnaid = data['dna_id']; //记录dna_id，用于更新库存表
                mass0 = data['mass']; //记录原来的使用量，用于更新库存表
                singleLB_id = data['singleLB_id'];
                // 获取对应的使用记录数据
                id2 = $.ajax({
                    url: url2, dataType: 'json', contentType: "application/json",
                    type: "get", async: false, data: {singleLB_id: singleLB_id}
                }).responseJSON[0];
                if (class_name === 'btn btn-info') {
                    // EDIT button
                    MyModelInit('更新', data);
                    $("#myModal").modal();
                } else {
                    // DELETE button
                    //alert('delete '+id);
                    //$('#modal_title').text('DELETE');
                    $("#confirm").modal();
                }

            });

            $('#modelForm').on('submit', function (e) {
                e.preventDefault();

                // 递交前检查，一般是检测model的外键是否存在
                let data0 = $.ajax({
                    url: url3, dataType: 'json', contentType: "application/json",
                    type: "get", async: false, data: {dna_id: $('#dna_id').val()}
                }).responseJSON[0];
                if (data0 === undefined) {
                    $('#myModalError').text('错误！！！DNA提取编号不存在，请填写正确的DNA提取编号。');
                    return
                }

                let type = $('#type').val();
                let method = '';
                let url_ajax = url;
                let url_ajax2 = url2;
                if (type === 'new') {
                    // new
                    method = 'POST';
                    // POST前检查，一般是检测model的关键字段值是否存在
                    let data1 = $.ajax({
                        url: url, dataType: 'json', contentType: "application/json",
                        type: "get", async: false, data: {singleLB_id: $('#singleLB_id').val()}
                    }).responseJSON[0];
                    if (data1 !== undefined) {
                        $('#myModalError').text('错误！！！建库编号已存在，无法添加。如需更新该条目，请在对应行进行更新操作。');
                        return
                    }
                } else {
                    // edit
                    url_ajax = url + id + '/';
                    url_ajax2 = url2 + id2.index + '/';
                    method = 'PUT';
                }

                // 增、改：更新建库表
                $.ajax({
                    url: url_ajax, async: false,
                    method: method,
                    data: $(this).serialize() + '&' + $.param({
                        sample_id: data0.sample_id
                    }),
                    headers: {'X-HTTP-Method-Override': 'PATCH'},
                    success: function () {
                        // 增、改：更新使用记录表
                        let data_tmp = $('#usageForm div input').serialize() + '&' + $.param({
                            sample_id: data0.sample_id, usage: '建库成功',
                            others: $('#others').val()
                        });
                        $.ajax({
                            url: url_ajax2,
                            method: method,
                            data: data_tmp,
                            headers: {'X-HTTP-Method-Override': 'PATCH'},
                            error: function (jqXHR, textStatus, errorThrown) {
                                console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                            }
                        });

                        // 更新库存表
                        let data_tmp2;
                        if (method === 'POST') {
                            data_tmp2 = $('#usageForm .InventoryForm input').serialize() + '&' + $.param({
                                sample_id: data0.sample_id,
                                totalM: data0.totalM,
                                successM: data0.successM + $('#mass').val(),
                                failM: data0.failM,
                                researchM: data0.researchM,
                                othersM: data0.othersM
                            });
                        } else {
                            sub = $('#mass').val() - mass0;
                            data_tmp2 = $('#usageForm .InventoryForm input').serialize() + '&' + $.param({
                                sample_id: data0.sample_id, totalM: data0.totalM, successM: data0.successM + sub,
                                failM: data0.failM, researchM: data0.researchM,
                                othersM: data0.othersM
                            });
                        }

                        $.ajax({
                            url: url3 + data0.index + '/',
                            method: 'PUT',
                            data: data_tmp2,
                            headers: {'X-HTTP-Method-Override': 'PATCH'},
                            error: function (jqXHR, textStatus, errorThrown) {
                                console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                            }
                        });

                        if (type === 'new') {
                            $('#myModalError').text('添加成功！！！建库编号：' + $('#singleLB_id').val());
                        } else {
                            $('#myModalError').text('更新成功！！！建库编号：' + $('#singleLB_id').val());
                        }

                        setTimeout(
                            function () {
                                location.reload();
                            }, 3000
                        );
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $('#myModalError').text('出现错误！！！请联系管理员');
                        console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                    }
                });

            });


            $('#confirm').on('click', '#delete', function (e) {
                // 删：删除建库表对应条目
                $.ajax({
                    url: url + id + '/',
                    method: 'DELETE',
                    success: function () {
                        // 删：删除使用记录表对应条目
                        $.ajax({
                            url: url2 + id2.index + '/',
                            method: 'DELETE',
                            error: function (jqXHR, textStatus, errorThrown) {
                                console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                            }
                        });

                        // 删： 库存表减去相应量
                        let data0 = $.ajax({
                            url: url3, dataType: 'json', contentType: "application/json",
                            type: "get", async: false, data: {dna_id: dnaid}
                        }).responseJSON[0];
                        let data_tmp2 = $.param({
                            dna_id: data0.dna_id, sample_id: data0.sample_id,
                            totalM: data0.totalM, successM: data0.successM - mass0,
                            failM: data0.failM, researchM: data0.researchM,
                            othersM: data0.othersM
                        });
                        $.ajax({
                            url: url3 + data0.index + '/',
                            method: 'PUT',
                            data: data_tmp2,
                            headers: {'X-HTTP-Method-Override': 'PATCH'},
                            success: function () {
                                location.reload();
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                            }
                        });
                        location.reload()
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                    }
                });
            });


            $('#new').on('click', function (e) {
                MyModelInit('新增', {});
                $("#myModal").modal();
            });


            $('#dna_id').blur(function () {
                $('#singleLB_id').val($('#dna_id').val() + "_m1");
            });

            $('#upload').on('click', function (e) {
                $('#uploadOperator').val("");
                $('#uploadFile').val("");
                $('#uploadError').val("");
                $('#uploadUrl').val('LibraryInfo');
                $("#uploadModal").modal();
            });

            $('#bulkDel').on('click', function (e) {
                $('#bulkDelUrl').val('LibraryInfo');
                $("#bulkDelModal").modal();
            });

            $('.downloadExcel').on('click', function (e) {
                e.preventDefault();
                window.location.href = '/download_excel/LibraryInfo/'
            });

            $('#myModalReset').on('click', function (e) {
                e.preventDefault();
                if ($('#modal_title').text() === '更新') {
                    MyModelInit('更新', dataModelForm);
                } else {
                    MyModelInit('新增', {});
                }
            });

            pie_plot('LibraryInfo', fieldForPie.val(), fieldForPie.find("option:selected").text());

            fieldForPie.change(function () {
                pie_plot('LibraryInfo', fieldForPie.val(), fieldForPie.find("option:selected").text());
            });
        })
    </script>
{% endblock %}